package com.hxk.ioText.byteIo.nodeIo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.hxk.ioText.bean.User;

public class ByteArrayIo {

	public static void main(String[] args) {
		byteArrayIo();
		stringByteArrayIo();
	}
	/**
	 * 字符串转二进制数组
	 * 二进制数组转字符串
	 */
	private static void stringByteArrayIo() {
		String str = "java 字节数据流";
		OutputStream os = null;
		InputStream is = null;
		try {
			os = new FileOutputStream("d:/b.txt");
			os.write(str.getBytes());
			is = new FileInputStream("d:/b.txt");
			byte[] buf = new byte[1024];
			int len = is.read(buf);
			String s = new String(buf, 0, len);
			System.out.println(s);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if(is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(os != null) {
					os.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private static void byteArrayIo() {
		ObjectInputStream ois = null;
		ObjectOutputStream oos = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(baos);
			oos.writeInt(123);
			oos.writeDouble(0.123);
			oos.writeBoolean(true);
			oos.writeUTF("java 数据流");
			oos.writeChar('a');
			oos.writeObject(new Date());
			User u = new User(1, "张三", "男", 18);
			oos.writeObject(u);
			
			ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
			int n = ois.readInt();
			System.out.println(n);
			double d = ois.readDouble();
			System.out.println(d);
			boolean b = ois.readBoolean();
			System.out.println(b);
			String s = ois.readUTF();
			System.out.println(s);
			char c = ois.readChar();
			System.out.println(c);
			Date date = (Date) ois.readObject();
			System.out.println(date);
			User user = (User) ois.readObject();
			System.out.println(user);
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(ois != null) {
					ois.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if(oos != null) {
					oos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
